package xyz.xiangyushui.controller.membership.reserveDesserts;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import xyz.xiangyushui.dao.user.member.CommodityReservableDao;
import xyz.xiangyushui.dao.user.member.ReservationHistoryDao;

/**
 * Servlet implementation class ReserveDetailGet
 */
@WebServlet("/member/reserveDesserts")
public class ReserveDetailGet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private final String emptyMsg="Incomplete form!";
	private final String invalidNum="Invalid quantity!";
	private final String stockLess="Stock not enough!";
	private ReservationHistoryDao rhd;
	private CommodityReservableDao crd;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ReserveDetailGet() {
        super();
        rhd=new ReservationHistoryDao();
        crd=new CommodityReservableDao();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String num=request.getParameter("num");
		String date_storeId=request.getParameter("date")+"_"+request.getParameter("storeId");
		String commodityIdName=request.getParameter("commodityIdName");
		String result=validater(num,date_storeId,commodityIdName);
		String returnUrl="/member/reserve/commodity"+"?"+"store="+date_storeId+"&&"+"id="+commodityIdName;
		
		System.out.println(result);
		if(result.equals("success")){
			//插入log
			rhd.addResevationRecord((String) request.getSession(false).getAttribute("userName"), date_storeId, commodityIdName,Integer.parseInt(num),new Date().getTime());
			
			//更新库存
			crd.updateStock(0-Integer.parseInt(num), date_storeId, commodityIdName);
			response.sendRedirect(request.getContextPath()+"/member/myReservation");
		}else{
			request.setAttribute("failedMsg", result);
			request.getRequestDispatcher(returnUrl).forward(request, response);
		}
	}
	
	private String validater(String num,String date_storeId,String commodityIdName){
		String msg="success";
		if("".equals(num)){
			msg=emptyMsg;
		}else{
			try{
				int number=Integer.parseInt(num);
				if(number<=0){
					msg=invalidNum;
				}else if(number>crd.getStock(date_storeId, commodityIdName)){
					msg=stockLess;
				}
			}catch (NumberFormatException e){
				msg=invalidNum;
			}
		}
		
		return msg;
	}

}
